/**
 * Created by shenhai on 15/9/14.
 */


angular.module('mis.appUserManager.controllers', [])
    .controller('appUserManagerCtrl', ['$scope','$http', '$location', function ($scope, $http, $location) {


        $scope.currentPage = 1;
        $scope.pageSize = 15;

        var GetRoleName = function(array) {

            array.forEach(function(temp) {
                var role='';
                for(r in temp.userRole){
                    if(temp.userRole[r]==1)role +='版主\n';
                    if(temp.userRole[r]==3)role +='雷锋团\n';
                }
                temp.userRoles = role;
            });
            return array;
        };



        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/appUser/appUserList/:page/:size',
            ajax: $http,
            success:function(data){
                $scope.userList = GetRoleName(data.data.list);
                console.log($scope.userList);
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
            },
            error: function(err){
                $scope.userList = null;
            },
            params: {}
        });


        $scope.search = function(current) {

            if (current) {
                $scope.currentPage = $scope.pagination.currentPage;
            }else {
                $scope.pagination.currentPage = 1;
                $scope.currentPage = 1;
            }

            var option = $scope.option;
            var city = $scope.cascading.getCity(document.getElementById("search-target"));
            var communityId = $scope.cascading.getVillageId(document.getElementById("search-target"));

            var body = {};
            if (city) body.cityId  = city;
            if (communityId) body.community = communityId;
            if (option && option.userId) body._id = option.userId;
            if (option && option.phone) body.mobilePhone = option.phone;
            if (option && option.nickName) body.nickName = option.nickName;
            if (option && option.authenticationStatus != null) body.authenticationStatus = option.authenticationStatus;
            if (option && option.talent) body.userType = option.talent;
            if (option && option.role) body.userRole = option.role;

            if ($("#startDate").val())  body.startDate = $("#startDate").val() + ' 00:00:00';
            if ($("#endDate").val())  body.endDate =  $("#endDate").val() + ' 23:59:59';

            if ($("#startDate").val() && $("#endDate").val() && $("#startDate").val() >$("#endDate").val()) {
                alert('开始日期不能大于结束日期');
                return;
            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/appUserList/' + $scope.currentPage + '/' + $scope.pageSize, body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                $scope.userList = GetRoleName(data.data.list);
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;

                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $scope.pagination.searchParams = body;

            }).error(function (err) {
                $scope.userList = null;
            });
        };

        //全选列表
        $scope.allSelected = function(){
            $scope.pagination.allSelected();
        };

        $scope.pullBlack= function(user, addData, black, index) {

            $scope.nickName = user.nickName;

            var body = {userID: user.objId, frozenOrNot:black};
            if (black && addData.reason)  body.reason = addData.reason;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/pullBlack', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (Number(data.result.status) == 1) {
                    user.frozenOrNot = black ? true : false;
                    if (black) {
                        $('#doc-modal-pullblackOK-'+ index).modal("close");
                    }else {
                        $('#doc-modal-pullblackCancel-'+ index).modal("close");
                    }
                }

            }).error(function () {

            });

        };



        /*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   start   */
        $scope.speakNotAllow= function(user, addData, gag, index) {

            $scope.nickName = user.nickName;

            var body = {userID: user.objId, gagOrNot:gag};
            if (gag && addData.reason)  body.reason = addData.reason;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/speakNotAllow', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (Number(data.result.status) == 1) {
                    user.gagOrNot = gag ? true : false;
                    if (gag) {
                        $('#doc-modal-speakNotAllowOK-'+ index).modal("close");
                    }else {
                        $('#doc-modal-speakNotAllowCancel-'+ index).modal("close");
                    }
                }

            }).error(function (error) {

            });

        };

        /*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   end   */

        /*  宝宝树66小区删除改造    add   luolh  20170929   start   */
        $scope.userDelete= function(user, addData, gag, index) {

            $scope.nickName = user.nickName;
            var body = {userID: user.objId, frozenOrNot:gag, delUserData:addData.delUserData};
            if (gag && addData.reason)  body.reason = addData.reason;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/appUserDelete', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (Number(data.result.status) == 1) {
                        user.frozenOrNot = gag ? true : false;
                        user.gagOrNot = gag ? true : false;
                        $('#doc-modal-userDelete-'+ index).modal("close");
                } else {
                    alert(data.result.message);
                }

            }).error(function () {
                // alert(error);
            });

        };
        /*  宝宝树66小区删除改造    add   luolh  20170929   end   */

        $scope.handleVStatus = function(user, isSetV ,index) {


            var body = {userID: user.objId, communityId:user.community.objId, authenticationStatus:isSetV};

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/modifyVAuthStatus', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (Number(data.result.status) == 1) {
                    user.authenticationStatus = isSetV ? true : false;
                    if (isSetV) {
                        $('#doc-modal-V-OK-'+ index).modal("close");
                    }else {
                        $('#doc-modal-V-Cancel-'+ index).modal("close");
                    }
                }
            }).error(function () {

            });

        };

        $scope.talentAction = function(user, addData, talent ,index) {


            var body = {userID: user.objId, talent:talent};
            if (talent && addData.talentDesc) body.talentDesc = addData.talentDesc;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/talent', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (Number(data.result.status) == 1) {
                    user.userType = talent ? 'talent' : 'normalAppUser';
                    if (talent) {
                        $('#doc-modal-talentOK-'+ index).modal("close");
                    }else {
                        $('#doc-modal-talentCancel-'+ index).modal("close");
                    }
                }
            }).error(function () {

            });
        };

        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170816   start   */
        // $scope.updateUserInfo = function(user, index,target) { // 旧
        $scope.updateUserInfo = function(user, index) { // 新
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170816   end   */
            var tmpUser = user;

            console.log(tmpUser);
            var body = {userID: user.objId, user:{}};
            if (user.gender) body.user.gender = user.gender;
            if (user.roomUnit) body.user.roomUnit = user.roomUnit;
            if (user.roomNumber) body.user.roomNumber = user.roomNumber;
            /*  宝宝树66小区二次改造    add   gct  20170802   start   */
            if(user.nickName)  body.user.nickName=user.nickName;
            if(user.mobilePhone) body.user.mobilePhone=user.mobilePhone;
            var oldCommunity = user.community.objId;
            var userRole=[];
            /*  宝宝树66小区二次改造    add   gct  20170802   end   */
            var provinceId = $("#cascad-edit-" + index).find(".c-provinces")[0].dataset.cId;
            var cityId = $("#cascad-edit-" + index).find(".c-citys")[0].dataset.cId;
            var countyId = $("#cascad-edit-" + index).find(".c-cityArea")[0].dataset.cId;
            var community = $("#cascad-edit-" + index).find(".c-village")[0].dataset.cId;
            /*  宝宝树66小区二次改造    add   gct  20170809   start   */
            var communityVal = $("#cascad-edit-" + index).find(".c-village")[0].value;

            /*  宝宝树66小区二次改造    add   gct  20170809   end   */
            //community=$('.c-provinces')[0].dataset.cId;

            if(community) {
                /*  宝宝树66小区二次改造    add   chenf  20170802   start   */
                if(oldCommunity != community){
                    body.user.userRole=userRole;
                }
                /*  宝宝树66小区二次改造    add   chenf  20170802   end   */

                body.user.community = community;
            }else{
                /*  宝宝树66小区二次改造    mod   gct  20170809   start   */
                body.user.userRole=userRole;
                 body.communityValue=communityVal;
                //alert(communityVal);
                 //alert('请选择小区');
                 //return;
                /*  宝宝树66小区二次改造    mod   gct  20170809   end   */
            }
            if(cityId) body.user.cityId = cityId;


            //console.log(community+":"+tmpUser.community.objId)
             //小区变动
            if(tmpUser.community) {
                body.isChangeCommunity = community != tmpUser.community.objId;
            }else{
                body.isChangeCommunity = true;
            }
            //console.log("有改动");
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/updateInfo', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                //var pageNumber = $(".am-active").text();//当前页码
                $('#doc-modal-Detail-'+ index).modal("close");
               /* $scope.search(true);*/
                /*  宝宝树66小区二次改造    mod   gct  20170817   start   */
                if (Number(data.result.status) == 1) {

                    if(data!=null&&typeof(data.data.status)!='undefined'&&Number(data.data.status)==999)
                    {
                        alert("请仔细确认小区名");
                    }

                    else {

                        alert('修改成功');
                    }

                }
                /*  宝宝树66小区二次改造    mod   gct  20170817   end   */
                else {
                    $('#doc-modal-Detail-'+ index).modal("close");
                    alert('修改失败');
                }
            }).error(function () {
                $('#doc-modal-Detail-'+ index).modal("close");
                alert('修改失败');
            });



            /*  宝宝树66小区二次改造    add   gct  20170802   start   */
            $('#doc-modal-Detail-'+ index).modal("close");
            $scope.search(true);
           /* window.location.href=window.location.href;*/
            /*  宝宝树66小区二次改造    add   gct  20170802   end   */
        };

        $scope.editClick = function(listData,index){
            $scope.cascading.paint($("#cascad-edit-"+index)[0],true);

            //if(listData.homeTown) {
            //
            //    $("#cascad-edit-" + index).find(".c-provinces").val(listData.homeTown.province.name);
            //    if (listData.homeTown.province) $("#cascad-edit-" + index).find(".c-provinces")[0].dataset.cId = listData.homeTown.province.objId;
            //    $("#cascad-edit-" + index).find(".c-citys").val(listData.homeTown.city.name);
            //    if (listData.homeTown.city) $("#cascad-edit-" + index).find(".c-citys")[0].dataset.cId = listData.homeTown.city.objId;
            //    if (listData.homeTown.country) {
            //        $("#cascad-edit-" + index).find(".c-cityArea").val(listData.homeTown.country.name);
            //        if (listData.homeTown.country) $("#cascad-edit-" + index).find(".c-cityArea")[0].dataset.cId = listData.homeTown.country.objId;
            //    };
            //};

            $("#cascad-edit-" + index).find(".c-village").val(listData.community.communityName);
            if (listData.community.communityName) $("#cascad-edit-" + index).find(".c-village")[0].dataset.cId = listData.community.objId;

        };

        $scope.editParents = function(listData,index){
            $scope.cascading.paint($("#cascad-parents-"+index)[0],true);


            //$("#cascad-parents-" + index).find(".c-provinces").val(listData.community.provinceName);
            //$("#cascad-parents-" + index).find(".c-citys").val(listData.community.cityeName);
            //$("#cascad-parents-" + index).find(".c-cityArea").val(listData.community.countyName);
            $("#cascad-parents-" + index).find(".c-village").val(listData.parentsCommunityName);
            if (listData.parentsCommunityName) $("#cascad-parents-" + index).find(".c-village")[0].dataset.cId = listData.parentsCommunity;
        };

        $scope.updateParents = function(user, index,temp){
            var target = temp.target;
            var body = {user: user.objId,type:2};

            var community = $("#cascad-parents-" + index).find(".c-village")[0].dataset.cId;
            if(community) {
                body.community = community;
            }else{
                alert('请选择小区');
                return;
            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/updateParents', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                var pageNumber = $(".am-active").text();//当前页码
                $('#doc-modal-parents-'+ index).modal("close");
                $scope.pagination.selectPage(pageNumber);

                if (Number(data.result.status) == 1) {
                    alert('修改成功');
                }else {
                    alert('修改失败');
                }
            }).error(function () {
                alert('修改失败');
            });


        };

        $scope.handleLFSRole = function(user, role ,index) {


            var body = {userID: user.objId, communityId:user.community.objId, userRole:role,huanxinUserName:user.huanxinUserName};

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/modifyUserRole', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (Number(data.result.status) == 1) {
                    user.userRoles = user.userRoles + '雷锋团';

                    $('#doc-modal-lf-'+ index).modal("close");

                }
            }).error(function () {

            });

        };

        $scope.exportUser = function(option, temp){
            var target = temp.target;

            var communityId = $scope.cascading.getVillageId(target);

            var href = 'http://' + backOfficeHost + '/rest/v1.0/mis/appUser/exportUser/?isValid=true';
            if (communityId) href += "&community="+communityId;
            if (option && option.userId) href += "&_id="+ option.userId;
            if (option && option.phone) href += "&mobilePhone="+ option.phone;
            if (option && option.nickName) href += "&nickName="+ option.nickName;
            if (option && option.authenticationStatus) href += "&authenticationStatus="+ option.authenticationStatus;
            if (option && option.talent) href += "&userType="+ option.talent;
            if (option && option.role) href += "&userRole="+ option.role;

            if ($("#startDate").val())  href += "&startDate=" + $("#startDate").val() + ' 00:00:00';
            if ($("#endDate").val())  href += "&endDate=" + $("#endDate").val() + ' 23:59:59';

            if(!$("#startDate").val() && !$("#endDate").val()){
                alert('请选择注册日期');
                return;
            }

            if ($("#startDate").val() && $("#endDate").val() && $("#startDate").val() >$("#endDate").val()) {
                alert('开始日期不能大于结束日期');
                return;
            }
            //console.debug(href);
            location.href = href;

        };

        $scope.getUserRole = function(userRole,role) {
            if(userRole.indexOf(role)==-1) {
                return false
            }else {
                return true;
            }
        };

        $scope.rejectRole = function(user,role,index) {

            var body = {userId: user.objId, userRole: role, community: user.community.objId};

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/appUser/rejectRole', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (data.result.status == 1) {
                    if(role == 1) {
                        $('#doc-modal-moderator-Cancel-'+ index).modal("close");
                    }else {
                        $('#doc-modal-leifeng-Cancel-' + index).modal("close");
                    }
                    $scope.search(true);
                } else {
                    if(role == 1) {
                        $('#doc-modal-moderator-Cancel-'+ index).modal("close");
                    }else {
                        $('#doc-modal-leifeng-Cancel-' + index).modal("close");
                    }
                    alert('操作失败！');
                }
            }).error(function (err) {
                if(role == 1) {
                    $('#doc-modal-moderator-Cancel-'+ index).modal("close");
                }else {
                    $('#doc-modal-leifeng-Cancel-' + index).modal("close");
                }
                alert(err);
            });

        };


        //级联框
        var cascadData = {
            provinceUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionPrivince',
            cityUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCity',
            cityAreaUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCounty',
            villageUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/communityList',
           /* villageUrl: 'http://' + backOfficeHost + '/rest/v1.0/mis/community/communityList',*/
            ajax: $http
        };
        $scope.cascading = new gObj.cascading(cascadData);
        $scope.cascading.paint($(".city-cascading")[0],true);

    }]);